<?php
  include("includes/header.php");
  $sql = "SELECT * FROM tb_portfolio WHERE id='$_GET[id]'";
  $query = mysql_query($sql);
  $result = mysql_fetch_array($query);
  $namaProject = $result["judul"];
  $gambarProject = $result["gambar"];
  $deskProject = $result["keterangan"];
  $linkProject = $result["link"];
  $codeProject = $result["code"];
  $id_portfolio = $result["id"];

  if($_GET["code"] == "update") {
    $id_portfolio = $_POST['idEdit'];
    $judul = $_POST['namaProject'];
    $keterangan = $_POST['deskProject'];
    $code = $_POST['codeProject'];
    $gambar = $_POST['gambarProject'];
    $link = $_POST['linkProject'];
    if ($link == "") {
      $link = "#";
    }

    $judul_low = strtolower($judul);
    $slug = str_replace(" ", "-", $judul_low);

    $sql = "UPDATE tb_portfolio SET judul = '$judul', keterangan = '$keterangan', gambar = '$gambar', link = '$link', slug = '$slug' WHERE id = '$id_portfolio'";
    $query = mysql_query($sql);

    $sql_update_image = "UPDATE tb_portfolio_image SET id_portfolio = $id_portfolio WHERE code = '$code'";
    $query_update_image = mysql_query($sql_update_image);

    $sql_select_image = "SELECT * FROM tb_portfolio_image WHERE id_portfolio IS NULL";
    $query_select_image = mysql_query($sql_select_image);
    if (mysql_num_rows($query_select_image) > 0) {
      $query_select_image = mysql_query($sql_select_image);
      while ($result_select_image = mysql_fetch_array($query_select_image)) {
        $code = $result_select_image['code'];
        unlink("../img/portfolio/".$result_select_image['code']."/".$result_select_image['gambar']);
        unlink("../img/portfolio/".$result_select_image['code']."/thumbnail/".$result_select_image['gambar']);
      }
      $dir = "../img/portfolio/".$code;
      $thumb_dir = "../img/portfolio/".$code."/thumbnail";

      if (is_dir($thumb_dir)) {
        $objects = scandir($thumb_dir);
        foreach ($objects as $object) {
          if ($object != "." && $object != "..") {
            unlink($thumb_dir."/".$object);
          }
        }
        reset($objects);
        rmdir($thumb_dir);
      }

      if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
          if ($object != "." && $object != "..") {
            unlink($dir."/".$object);
          }
        }
        reset($objects);
        rmdir($dir);
      }
      $sql_delete_image = "DELETE FROM tb_portfolio_image WHERE id_portfolio IS NULL";
      $query_delete_image = mysql_query($sql_delete_image);
    }

    echo "<script>window.location.href='portfolio-edit.php?id=".$id_portfolio."&code=edit';</script>";
  }
?>
<div class="col-xs-10 col-xs-offset-2 content-container">
  <div class="page-header">
    <h3>Portfolio</h3>
  </div>
  <ol class="breadcrumb">
    <li><a href="portfolio.php">Portfolio</a></li>
    <li class="active">Edit</li>
  </ol>
  
  <form action="portfolio-edit.php?id=<?php echo $_GET['id']; ?>&code=update" method="post" enctype="multipart/form-data" onsubmit="return cekForm()">
    <input type="hidden" name="idEdit" value="<?php echo $_GET['id']; ?>">
    <div class="form-group">
      <label>Nama Project</label>
      <input type="text" class="form-control" id="namaProject" name="namaProject" value="<?php echo $namaProject; ?>">
      <input type="hidden" id="codeProject" name="codeProject" value="<?php echo $codeProject; ?>">
      <input type="hidden" id="gambarProject" name="gambarProject" value="<?php echo $gambarProject ?>">
    </div>

    <div class="form-group">
      <label>Link Project</label>
      <input type="text" class="form-control" id="linkProject" name="linkProject" value="<?php echo $linkProject ?>">
    </div>

    <div class="form-group">
      <span class="btn btn-info" id="upload-image"><i class="glyphicon glyphicon-upload"></i>Upload Image</span>
      <input type="hidden" id="valid-upload" value="0">
    </div>

    <div id="image-placer">
      
    </div>

    <div class="form-group">
      <label>Deskripsi</label>
        <textarea class="form-control" id="deskProject" name="deskProject"><?php echo $deskProject; ?></textarea>
    </div>
    <input type="submit" class="btn btn-primary" value="Submit">
  </form>
</div>
<?php
  include("includes/footer.php");
?>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Peringatan</h4>
      </div>
      <div class="modal-body">
        <input type="hidden" class="idDelete">
        <span class="isiModal"></span>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="modalUploadGambar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Upload Images</h4>
      </div>
      <div class="modal-body">
        <!-- The file upload form used as target for the file upload widget -->
        <form id="fileupload" action="//jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data">
          <!-- Redirect browsers with JavaScript disabled to the origin page -->
          <noscript><input type="hidden" name="redirect" value="http://blueimp.github.io/jQuery-File-Upload/"></noscript>
          <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
          <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
              <!-- The fileinput-button span is used to style the file input field as button -->
              <span class="btn btn-success fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files...</span>
                <input type="file" name="files[]" multiple>
              </span>
              <button type="submit" class="btn btn-primary start">
                <i class="glyphicon glyphicon-upload"></i>
                <span>Start upload</span>
              </button>
              <input type="checkbox" class="toggle">
              <!-- The global file processing state -->
              <span class="fileupload-process"></span>
            </div>
            <!-- The global progress state -->
            <div class="col-lg-5 fileupload-progress fade">
              <!-- The global progress bar -->
              <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                  <div class="progress-bar progress-bar-success" style="width:0%;"></div>
              </div>
              <!-- The extended global progress state -->
              <div class="progress-extended">&nbsp;</div>
            </div>
          </div>
          <!-- The table listing the files available for upload/download -->
          <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" id="finishUpload" class="btn btn-default" data-dismiss="modal">Save changes</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
  {% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
      <td><span class="preview"></span></td>
      <td>
        <p class="name">{%=file.name%}</p>
        <strong class="error text-danger"></strong>
      </td>
      <td>
        <p class="size">Processing...</p>
        <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
      </td>
      <td>
        {% if (!i && !o.options.autoUpload) { %}
          <button class="btn btn-primary start" disabled style="display: none;">
            <i class="glyphicon glyphicon-upload"></i>
            <span>Start</span>
          </button>
        {% } %}
        {% if (!i) { %}
          <button class="btn btn-warning cancel">
            <i class="glyphicon glyphicon-ban-circle"></i>
            <span>Cancel</span>
          </button>
        {% } %}
      </td>
    </tr>
  {% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
</script>


<script type="text/javascript">
  function cekForm() {
    namaProject = $('#namaProject').val();
    gambarProject = $('#gambarProject').val();
    deskProject = CKEDITOR.instances.deskProject.getData();

    if(namaProject == '' || gambarProject == '' || deskProject == '') {
      $('.isiModal').html('Maaf, mohon melengkapi form yang telah disediakan.');
      $('#myModal').modal('show');
      return false;
    } else {
      var jumlah_image = $('#image-placer').find('.img-tile').length;
      if (jumlah_image > 0) {
        if ($('#gambarProject').val() != "") {
          return true;
        } else {
          $('.isiModal').html('Tentukan gambar default terlebih dahulu.');
          $('#myModal').modal('show');
          return false;  
        };
      } else {
        $('.isiModal').html('Masukkan gambar terlebih dahulu.');
        $('#myModal').modal('show');
        return false;  
      };
    }
  }

  function get_image() {
    $.ajax({
      url: 'get-image.php',
      type: 'POST',
      data: {
        code: $('#codeProject').val(),
        act: 'edit'
      },
      beforeSend: function(data) {
        console.log("sending");
      },
      success: function(data) {
        $('#image-placer').html(data);
      },
      complete: function(data) {
        console.log("complete");
      },
      error: function(data) {
        console.log("error");
      }
    })
  }

  $(document).ready(function() {
    get_image();

    CKEDITOR.replace( 'deskProject', {
      toolbar : [
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ], items: [ 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo' ] },
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'align' ], items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
        { name: 'links', items: [ 'Link', 'Unlink' ] },
        { name: 'insert', items: [ 'Table', 'SpecialChar' ] },
        { name: 'styles', items: [ 'FontSize' ] },
        { name: 'colors', items: [ 'TextColor' ] }
      ]
    });

    'use strict';

    $('#upload-image').click(function(event) {
      $('#modalUploadGambar').modal("show");
    });
    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
      // Uncomment the following to send cross-domain cookies:
      //xhrFields: {withCredentials: true},
      url: 'includes/upload-image.php',
      type: "POST"
    });
    $('#fileupload').bind('fileuploadsubmit', function (e, data) {
      // The example input, doesn't have to be part of the upload form:
      // var input = $('#input');
      data.formData = {
        code: $('#codeProject').val(),
        act: "review"
      };
    });
    $('#finishUpload').click(function(event) {
      $('#valid-upload').val("1");
      get_image();
    });

    $('#image-placer').on('mouseenter', '.img-tile', function(event) {
      $(this).find('.image-default').show();
    });

    $('#image-placer').on('mouseleave', '.img-tile', function(event) {
      if ($(this).find('.is_default').val() == 0) {
        $(this).find('.image-default').hide();
      };
    });

    $('#image-placer').on('click', '.image-default', function(event) {
      $('.image-default').hide();
      $('.is_default').val(0);
      $(this).show();
      $(this).closest('.img-tile').find('.is_default').val('1');
      var jumlah_image = $('#image-placer').find('.img-tile').length;
      $('#gambarProject').val($(this).closest('.img-tile').find('.img_name').val());
    });

    $('#image-placer').on('click', '.del-image', function(event) {
      event.preventDefault();
      var that = $(this);
      var r = confirm('Apakah anda yakin untuk menghapus item ini?');
      if (r == true){
        $.ajax({
          url: 'portfolio-delete-image.php',
          type: 'POST',
          data: {
            id: $(this).closest('.img-tile-placer').find('.id_portfolio_image').val()
          },
          beforeSend: function(data) {
            console.log("sending");
          },
          success: function(data) {
            that.closest('.img-tile-placer').remove();
          },
          complete: function(data) {
            console.log("complete");
          },
          error: function(data) {
            console.log("error");
          }
        })
        return false;
      }else{
        return false;
      }
    });
  });
</script>